//
//  YBRefreshControl.swift
//  Weibo
//
//  Created by yinbo on 2018/3/27.
//  Copyright © 2018年 yinbo. All rights reserved.
//

import UIKit
private let YBRefreshOffset:CGFloat = 160
enum YBRefreshState{
    case Normal
    case Pulling
    case WillRefresh
}
class YBRefreshControl: UIControl {
    //MARK:-属性
    //滚动视图的父视图，下拉刷新控件应该适用于uitableview/uicollectionview
    weak var scrollView:UIScrollView?
    lazy var refreshview:YBMeiTuanRefreshView = YBMeiTuanRefreshView.refreshView() as! YBMeiTuanRefreshView
//    lazy var refreshview:YBRefreshView = YBRefreshView.refreshView()
    func beginRefreshing(){
        guard let sv = scrollView else {
            return
        }
        
        if refreshview.refreshState == .WillRefresh{
            return
        }
        //设置刷新视图状态
        refreshview.refreshState = .WillRefresh
        //调整表格间距
        var inset = sv.contentInset
        inset.top += YBRefreshOffset
        sv.contentInset = inset
    }
    func endRefreshing(){
        
        guard let sv = scrollView else {
            return
        }
        
        if refreshview.refreshState != .WillRefresh{
            return
        }
        //设置刷新视图状态
        refreshview.refreshState = .Normal
        //调整表格间距
        var inset = sv.contentInset
        inset.top -= YBRefreshOffset
        sv.contentInset = inset
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        fatalError("init(coder) has not beeen implemented")
        setupUI()
    }
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        guard let sv = newSuperview as?UIScrollView else {
            return
        }
        scrollView = sv
        //kVO监听父视图的contentoffset
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
        print(newSuperview)
    }
    override func removeFromSuperview() {
        superview?.removeObserver(self, forKeyPath:"contentOffset")
        super.removeFromSuperview()
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        print(scrollView?.contentOffset)
        guard let sv = scrollView else {
            return
        }
        //初始高度就应该为0
        let height = -(sv.contentInset.top + sv.contentOffset.y)
        if height<0{
            return
        }
        refreshview.parentViewHeight = height
        if sv.isDragging{
            if height>YBRefreshOffset && refreshview.refreshState      == .Normal{
                print("放手刷新")
                refreshview.refreshState = .Pulling
            }else if height <= YBRefreshOffset && (refreshview.refreshState == .Pulling){
                print("在使劲")
                refreshview.refreshState = .Normal
            }
        }else{
            //放手
            if refreshview.refreshState == .Pulling{
                print("准备开始刷新")
//                refreshview.refreshState = .WillRefresh
//                var inset = sv.contentInset
//                inset.top += YBRefreshOffset
//                sv.contentInset = inset
                beginRefreshing()
                sendActions(for: .valueChanged)
            }
        }
        self.frame = CGRect(x: 0, y:-height, width: sv.bounds.width, height: height)
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
}

extension YBRefreshControl{
    func setupUI(){
//        backgroundColor = UIColor.orange
        backgroundColor = superview?.backgroundColor
        addSubview(refreshview)
        refreshview.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: refreshview, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshview, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshview, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshview.bounds.width))
        addConstraint(NSLayoutConstraint(item: refreshview, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshview.bounds.height))
    }
}
